package com.wstuo.common.config.cab.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.wstuo.common.config.cab.dao.CABDAO;
import com.wstuo.common.config.cab.dao.ICABMemberDAO;
import com.wstuo.common.config.cab.dto.CABMemberDTO;
import com.wstuo.common.config.cab.entity.CAB;
import com.wstuo.common.config.cab.entity.CABMember;
import com.wstuo.common.security.dao.IUserDAO;

/**
 * 变更委员会成员Service
 * @author WSTUO
 *
 */
public class CABMemberService implements ICABMemberService {

	@Autowired
	private ICABMemberDAO cabMemberDAO;
	@Autowired
	private CABDAO cabDAO;
	@Autowired
	private IUserDAO userDAO;
	/**
	 * 保存CABMember
	 * @param cabMembeDto
	 */
	@Transactional
	public void saveCABMember(CABMemberDTO cabMembeDto){
		CABMember cabMember=new CABMember();
		
		cabMember.setDescription(cabMembeDto.getDesc());
		if(cabMembeDto.getApprovalMember()!=null){
			cabMember.setApprovalMember(userDAO.findById(cabMembeDto.getApprovalMember()));
		}
		if(cabMembeDto.getDelegateMember()!=null){
			cabMember.setDelegateMember(userDAO.findById(cabMembeDto.getDelegateMember()));
		}
		cabMemberDAO.save(cabMember);
		
		if(cabMembeDto.getCabId()!=null){
			CAB cab=cabDAO.findById(cabMembeDto.getCabId());
			if(cab.getCabMember()!=null){
				cab.getCabMember().add(cabMember);
			}else{
				List<CABMember> list = new ArrayList<CABMember>();
				list.add(cabMember);
				cab.setCabMember(list);
			}
			
			cabDAO.merge(cab);
		}
		
		cabMembeDto.setCabMemberId(cabMember.getCabMemberId());
		
	}
	
	/**
	 * 编辑CABMember
	 * @param cabMembeDto
	 */
	@Transactional
	public void editCABMember(CABMemberDTO cabMembeDto){
		CABMember cabMember=cabMemberDAO.findById(cabMembeDto.getCabMemberId());
		cabMember.setDescription(cabMembeDto.getDesc());
		if(cabMembeDto.getApprovalMember()!=null){
			cabMember.setApprovalMember(userDAO.findById(cabMembeDto.getApprovalMember()));
		}else{
			cabMember.setApprovalMember(null);
		}
		if(cabMembeDto.getDelegateMember()!=null){
			cabMember.setDelegateMember(userDAO.findById(cabMembeDto.getDelegateMember()));
		}else{
			cabMember.setDelegateMember(null);
		}
		
		cabMemberDAO.merge(cabMember);
	}
	
	/**
	 * 删除CABMember
	 * @param cabId
	 * @param cabMemberIds
	 */
	@Transactional
	public void deleteCABMember(final Long cabId,final Long[] cabMemberIds){
		CAB cab=cabDAO.findById(cabId);
		if(cabMemberIds!=null && cab.getCabMember()!=null){
			for(Long id:cabMemberIds){
				CABMember cabMember=cabMemberDAO.findById(id);
				if(cab.getCabMember().contains(cabMember)){
					cab.getCabMember().remove(cabMember);
				}
			}
		}
		cabMemberDAO.deleteByIds(cabMemberIds);
		cabDAO.merge(cab);
	};
	
	
}
